/**
 * 移动端路由生成
 */
import CommonUtil from '../utils/common'
import ArrayUtil from '../utils/array'
import { cloneDeep, omitBy } from 'lodash'
import URLUtil from '../utils/url'
import clone from 'clone'

const MICRO_APP_REGEXP = /{microapp:[a-z, A-Z,-,/]+}/,
  PATH_REGEXT = /\/:{path:[a-z, A-Z,-, 0-9]+}/,
  PLACEHOLDER_REGEXP = /{[a-z, A-Z,-]+:[a-z, A-Z,-]+}/g,
  ROOT_REGEXP = /\/{root:[a-z, A-Z,-,/]+}/

export default (dataList, router) => {
  const routeMap = router.flatRoutes(clone(router.getRouteConfig())),
    actionMap = {}, routePathMap = {}, rootList = router.getRootList(), rootMap = {}
  let defaultRoot = null

  rootList.map(root => {
    rootMap[root.path] = root
    const root_children = root.children || []
    root.children = []
    const routes = router.flatRoutes(clone(root_children))
    Object.keys(routes).map(k => {
      root.children.push(routes[k])
    })
    if (root.path == '/' || root.path == '') {
      defaultRoot = root
      // buildLocalRouteMenu(root_children, root).map(menu => {
      //   defaultRootStaticMenuList.push(menu)
      // })
    }
  })

  // 缓存按钮权限
  dataList.map(data => {
    if (data.type === '3') {
      actionMap[data.parentId] = actionMap[data.parentId] || []
      actionMap[data.parentId].push(data.code.split(':').pop())
    }
  })

  dataList.map(data => {
    let query = null,
      url = null
    if (data.mobileUrl) {
      query = URLUtil.getURLParams(data.mobileUrl) || {}
      url = data.mobileUrl.split('?')[0]
    }
    if (!url) {
      return
    }
    if (data.target === '4') {
      // 构建微应用
      const config = JSON.parse(url)
      if (routePathMap[config.code]) {
        return
      }
      const route = router.buildMicroApp(config)
      rootMap[config.root].children.push(route)
      route.meta._parent = rootMap[config.root]
      routePathMap[config.code] = true
      return
    }
    if (!url.startsWith('/')) {
      return
    }
    const path_match = url.match(PATH_REGEXT)
    if (path_match) {
      // 匹配到动态路由
      // const path_match_split = path_match[0].substring(3, path_match[0].length - 1).split(':')
      // menu.path = menu.path.replace(PATH_REGEXT, `/${path_match_split[1]}`)
      return
    }
    if (query.menuId) {
      return
    }
    let route = routeMap[url]
    if (!route) {
      console.error(`找不到对应路由配置信息: ${url}`)
      return
    }
    // 合并菜单 meta 到路由
    CommonUtil.merge(route.meta, {
      key: data.id,
      id: data.id,
      parentId: data.parentId,
      title: data.name,
      hidden: data.type == '3' ? true : CommonUtil.toBool(data.hidden),
      icon: data.icon,
      type: data.type
    })
    // 转存在 path 路径上配置的参数
    query && (route.query = query)

    // 添加功能权限
    route.meta.authorize = actionMap[route.meta.id] || []
    // 移除该路由下没有path的子节点
    if (route.children) {
      route.children = route.children.filter(child => child.path)
    }
    defaultRoot.children.push(route)
  })

  // 设置默认根路由的重定向地址
  defaultRoot.children.find(child => {
    return setDefaultRedirect(defaultRoot, child)
  })

  return { rootList }
}

function setDefaultRedirect (root, child) {
  if (root.redirect) {
    return true
  }
  if (!child.meta?.hidden && child.path && child.path.indexOf('/:') == -1) {
    root.redirect = child.path
    return true
  } else if (child.children) {
    child.children.find(child => {
      return setDefaultRedirect(root, child)
    })
  }
  return false
}